package cn.piesat.client.listener;

import cn.piesat.client.constant.cache.LocalCache;
import cn.piesat.client.model.dto.base.algorithm.DMSClientBean;
import cn.piesat.client.service.SateService;
import cn.piesat.client.utils.ReadMapFormatUtil;
import cn.piesat.client.utils.ReadPropertiesUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 算法文件夹监听实现类
 * 用于监听算法配置文件夹,对算法配置的及时处理
 * @author liuyang
 */
public class AlgorithmListener extends FileAlterationListenerAdaptor {

    private static Logger logger= LoggerFactory.getLogger(AlgorithmListener.class);

    private SateService sateService;

    public AlgorithmListener(SateService sateService){
        this.sateService = sateService;
    }

    /**
     * 新算法文件创建
     * 1.读取该文件信息
     * 2.添加本地缓存
     * 3.向reids汇报最新算法信息
     * @param file
     */
    @Override
    public void onFileCreate(File file) {
        ReadPropertiesUtil readUtil = new ReadPropertiesUtil();
        try {
            Map<String, String> read = readUtil.read(file);
            DMSClientBean dmsClientBean = ReadMapFormatUtil.formatDmsClientBean(read);
            if(dmsClientBean!=null){
                LocalCache.algorithmCache.put(dmsClientBean.getAlgorithmBean().getAlgorithmIdEng(),dmsClientBean);
                //redis注册
                sateService.pushNewAlgorithmInfo(dmsClientBean);
            }
            logger.info("FileCreate:{}",file.getName());
        } catch (IOException e) {
            logger.error("FileCreate Error:{},errorMsg:{}",file.getName(),e.getMessage());
        }
    }

    /**
     * 算法文件更新：
     * 1.读取该文件信息
     * 2.更新本地缓存
     * 3.向reids汇报最新算法信息
     * @param file
     */
    @Override
    public void onFileChange(File file) {
        ReadPropertiesUtil readUtil = new ReadPropertiesUtil();
        try {
            Map<String, String> read = readUtil.read(file);
            DMSClientBean algorithmBean = ReadMapFormatUtil.formatDmsClientBean(read);
            if(algorithmBean!=null){
                LocalCache.algorithmCache.put(algorithmBean.getAlgorithmBean().getAlgorithmIdEng(),algorithmBean);
                //redis注册
                sateService.pushNewAlgorithmInfo(algorithmBean);
            }
            logger.info("FileUpdate:{}",file.getName());
        } catch (IOException e) {
            logger.error("FileUpdate error:{},errorMsg:{}",file.getName(),e.getMessage());
        }

    }

    /**
     * 算法文件删除
     * 1.删除本地缓存
     * 2.删除redis上信息
     * @param file
     */
    @Override
    public void onFileDelete(File file) {
        LocalCache.algorithmCache.remove(FilenameUtils.removeExtension(file.getName()));
        //删除redis上信息(待确认)
        logger.info("FileDelete:{}",file.getName());
    }

}
